<?php

namespace app\service\admin;


use app\model\Common;
use app\tools\Workerman;
use app\tools\WxOffiaccount;
use app\tools\WxPlatform;
use Exception;
use TencentCloud\Captcha\V20190722\CaptchaClient;
use TencentCloud\Captcha\V20190722\Models\DescribeCaptchaResultRequest;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use think\cache\driver\Redis;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Session;
use think\Model;

/**
 * Class LoginService
 * @package projects\services\admin
 * @author Du
 * @date 2021/2/25
 * @time 16:18
 */
class LoginServices
{

    /**
     * 获取网站设置
     *
     * User : Du
     * Date : 2022/1/8
     * Time : 11:04
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function webData()
    {
        $data = cache()->get('LoginData');
        if ($_SERVER['SERVER_ADDR'] === '127.0.0.1' || !$data) {
            $data = Common::getData(WebsiteTable, ['id' => 1], ['name', 'desc', 'copyright', 'domain', 'start_time']);
            if (!$data['copyright']) {
                $data['copyright'] = date('Y');
            } else {
                $data['copyright'] = $data['copyright'] . '-' . date('Y');
            }
            if ($data['start_time'] !== 0) {
                $time = time() - $data['start_time'];
                $day = floor($time / 86400);
                $hour = floor(($time - ($day * 86400)) / 3600);
                $minute = floor(($time - ($day * 86400) - ($hour * 3600)) / 60);
                $second = floor($time - ($day * 86400) - ($hour * 3600) - ($minute * 60));
            } else {
                $day = 0;
                $hour = 0;
                $minute = 0;
                $second = 0;
            }
            $data['d'] = $day;
            $data['H'] = $hour;
            $data['i'] = $minute;
            $data['s'] = $second;
            cache()->set('LoginData', $data, 7200);
        }
        return $data;
    }

    /**
     * 检测用户登录信息
     *
     * User : Du
     * Date : 2022/3/10
     * Time : 16:10
     * @param array $request
     * @return bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function checkUserLogin(array $request)
    {
        //极验滑动验证
        if (!self::checkCode($request)) {
            return '验证失败，请重新点击验证！';
        }
        $field = ['id', 'account', 'avatar', 'password', 'status'];
        $res = Common::getData(AdminTable, ['account' => $request['username']], $field);
        if ($res && password_verify($request['password'], $res['password'])) {
            if ($res['status'] !== 1) {
                return '该账号已禁止登录';  //禁止登陆
            }
            Common::fieldInc(AdminTable, ['id' => $res['id']], 'login_number');
            Common::addData(AdminLoginTable, ['admin_id' => $res['id'], 'type' => 1, 'status' => 1, 'ip' => getIp()]);
            $res['login_time'] = time();
            if ($res['avatar']) {
                $res['avatar'] = imagePath($res['avatar'])['src'];
            }
            session('manage_info', $res);
            cache('Manage_' . $res['id'], $res);
            return true;
        }
        return '账号或密码错误，请重新尝试！';
    }

    /**
     * 极验证行为验证
     *
     * User : Du
     * Date : 2022/7/4
     * Time : 11:25
     * @param array $request
     * @return bool
     */
    public static function checkCode(array $request): bool
    {
        if ($_SERVER['SERVER_ADDR'] === '127.0.0.1') {
            return true;
        }
        //参数配置
        $captcha_id = env('geetest.captchaid');
        $captcha_key = env('geetest.captchakey');
        $api_server = env('geetest.captchaurl');
        //组合数据
        $data = [
            "lot_number" => $request['lot_number'],
            "captcha_output" => $request['captcha_output'],
            "pass_token" => $request['pass_token'],
            "gen_time" => $request['gen_time'],
            "sign_token" => hash_hmac('sha256', $request['lot_number'], $captcha_key),   //签名生成
        ];
        $url = sprintf($api_server . "/validate" . "?captcha_id=%s", $captcha_id);
        $data = http_build_query($data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => "Content-type: application/x-www-form-urlencoded",
                'content' => $data,
                'timeout' => 5
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $result = jsonToArray($result);
        if ($result['result'] === 'success') {
            return true;
        }
        return false;
    }

    /**
     * 微信扫码登陆
     *
     * @param array $data
     * @return array|string
     */
    public static function WxScanCode(array $data)
    {
        $data = [
            'type' => 1,
        ];
        $id = Common::addData(AdminWxLogTable, $data, true);
        $res = WxPlatform::getWxtTicketUrl($id);
        if (!$res) {
            return '请求失败，请检查微信配置';
        }
        return $res;
    }

    /**
     * 微信扫码状态
     *
     * @param array $data
     * @return bool|array
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function ScanCodeStatus(array $data)
    {
        $res = Common::getData(WxQrTable, ['id' => $data['id']], ['id', 'user_id', 'status', 'create_time']);
        if (!$res || $res['create_time'] < time() - 300) {
            return false;
        }
        switch ($res['status']) {
            case 0:
                $text = '未扫码';
                break;
            case 1:
                $text = '登陆成功';
                //登陆成功
                $field = ['id', 'user_name', 'avatar', 'password', 'status'];
                $userInfo = Common::getData(UserTable, ['id' => $res['user_id']], $field);
                Common::fieldInc(UserTable, ['id' => $res['user_id']], 'login_number',);
                $userInfo['login_time'] = time();
                if ($userInfo['avatar']) {
                    $userInfo['avatar'] = env('qiniu.domain') . $userInfo['avatar'];
                }
                session('manage_info', $userInfo);
                cache('Manage_' . $userInfo['id'], $userInfo);
                break;
            case 11:
                $text = '账号已禁用';
                break;
            case 10:
                $text = '该微信未绑定账号';
                break;
            default:
                $text = '未知状态';
        }
        return [
            'status' => $res['status'],
            'text' => $text,
        ];

    }

    /**
     * 缓存客户端id更新在线人数
     * @param array $request
     * @return bool
     * @throws Exception
     */
    public static function updateCount(array $request): bool
    {
        $clientId = $request['client_id'];
        if (Workerman::isOnline($clientId)) {
            $sessionId = Session::getId();
            //加入项目分组
            Workerman::joinGroup($clientId);
            //绑定session_id
            Workerman::bingUser(['client_id' => $clientId, 'id' => $sessionId]);
        }
        updateOnline();
        return true;
    }

}